import Aedes from 'aedes'
import net from 'node:net'
import MQTT from 'mqtt'
import config from './config.json' assert { type: 'json' }
import { MQTT_TOPIC } from './constant.js'

const { brokerPath, port } = config.mqtt
const aedes = Aedes()
const broker = net.createServer(aedes.handle)
const randomStr = () => {
    return [...Array(10)].map(() => Math.random().toString(36)[2] || '0').join('');
}

function sendUserRegister() {
    const brokerURL = `${brokerPath}:${port}`
    const randomAccount = randomStr()
    const data = JSON.stringify({
        account: randomAccount,
        password: '12345678',
        email: `${randomAccount}@gmail.com`,
        age: 15
    })
    const client = MQTT.connect(brokerURL, { id: 'for-test-user-register' })
    client.on('connect', async () => {
        await client.publishAsync(MQTT_TOPIC.USER_REGISTER, data)
        client.end()
    })
}

broker.listen(port, () => {
    console.log('[MQTT BROKER] running in 1883')
})

aedes.on('client', (client) => {
    console.log(`[MQTT BROKER] connected client id: ${client.id}`)
})

aedes.on('clientDisconnect', (client) => {
    console.log(`[MQTT BROKER] client disconnect id: ${client.id}`)
})

aedes.on('publish', (packet, client) => {
    const { topic, payload } = packet
    const { id } = client || {}

    let payloadText = ''
    if (Buffer.isBuffer(payload) || payload?.type === 'Buffer') payloadText = payload.toString()
    else if ( typeof payload === 'object') payloadText = JSON.stringify(payload)
    else payloadText = payload
    console.log(`[MQTT BROKER] publish, ${id ? `clientId: ${id}; ` : ''} topic: ${topic}; payload: ${payloadText}`)

    if (topic === MQTT_TOPIC.SYSTEM_AVAILABILITY) {
        sendUserRegister()
    }
})
